package com.szxb.facebus.base;

import android.annotation.SuppressLint;
import android.graphics.Color;
import android.graphics.drawable.AnimationDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.szxb.facebus.BuildConfig;
import com.szxb.facebus.BusApp;
import com.szxb.facebus.R;
import com.szxb.facebus.db.entity.bean.QRScanMessage;
import com.szxb.facebus.db.manager.DBManager;
import com.szxb.facebus.intrefaces.OnDownProgress;
import com.szxb.facebus.task.remote.CheckApkThread;
import com.szxb.facebus.task.work.WorkThread;
import com.szxb.facebus.util.basics.AppUtils;
import com.szxb.facebus.util.basics.Constant;
import com.szxb.facebus.util.basics.CountTime;
import com.szxb.facebus.util.basics.DateUtil;
import com.szxb.facebus.util.log.SLog;
import com.szxb.facebus.util.rx.RxBus;
import com.szxb.facebus.util.schedule.ThreadFactory;
import com.szxb.facebus.util.sound.SoundPoolUtil;
import com.szxb.facebus.util.toast.BusToast;
import com.szxb.facebus.util.view.CircleLayout;
import com.tencent.deepsea.camera.CameraPreview;
import com.tencent.txccm.base.utils.LogUtil;
import com.tencent.wlxsdk.FaceResult;
import com.tencent.wlxsdk.WlxSdk;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * 作者：Tangren on 2018-12-04
 * 包名：com.szxb.facebus.base
 * 邮箱：996489865@qq.com
 * TODO:一句话描述
 */

public abstract class BaseActivity extends AppCompatActivity implements OnDownProgress, WlxSdk.FaceRecognitionCallBack {

    private CheckApkThread checkApkThread;

    private TextView progress_text;
    private TextView version;
    private CircleLayout mContainer;
    private CameraPreview mCameraView;
    private ImageView scan_status;
    private TextView scan_res;

    private TextView time;

    private Disposable subscribe;

    private AnimationDrawable waitDrawble;
    /**
     * 0：新延迟任务
     * 1：正在执行延迟任务
     * -1:无延迟任务
     */
    private AtomicInteger resumeFlag = new AtomicInteger(-1);
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            String currentTime = String.format("%1$s", DateUtil.getMainTime());
            time.setText(currentTime);
        }
    };

    protected abstract int rootView();

    protected abstract void initData();

    protected abstract void message(QRScanMessage message);

    protected void initView() {
        time = findViewById(R.id.time);
        progress_text = findViewById(R.id.progress_text);
        version = findViewById(R.id.version);
        version.setText(BuildConfig.VERSION_NAME);
        mContainer = findViewById(R.id.texture);
        scan_status = findViewById(R.id.scan_status);
        scan_res = findViewById(R.id.scan_res);
        mCameraView = new CameraPreview(this, null);
        WlxSdk.startFaceRecognition(mCameraView, getLifecycle(), this);
        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(1000, 1000);
        params.gravity = Gravity.CENTER;
        mCameraView.setLayoutParams(params);
        mContainer.addView(mCameraView);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        if (Build.VERSION.SDK_INT > 21) {
            int option = View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                    | View.SYSTEM_UI_FLAG_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;

            getWindow().getDecorView().setSystemUiVisibility(option);
            getWindow().setNavigationBarColor(Color.TRANSPARENT);
        }
        super.onCreate(savedInstanceState);
        setContentView(rootView());
        initView();

        initRx();

        initData();
        checkApkThread = new CheckApkThread();
        checkApkThread.setOnDownProgress(this);
        initDate();
//        ThreadFactory.getScheduledPool().executeCycle(checkApkThread, 20, 20, "loop_check", TimeUnit.SECONDS);
    }


    private void initDate() {
        ThreadFactory.getScheduledPool().executeCycle(new Runnable() {
            @Override
            public void run() {
                mHandler.sendEmptyMessage(Constant.TIME_CODE);
            }
        }, 0, 1, "TIME", TimeUnit.MINUTES);
    }

    private void initRx() {
        subscribe = RxBus.getInstance().toObservable(QRScanMessage.class)
                .onBackpressureDrop()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<QRScanMessage>() {
                    @Override
                    public void accept(@NonNull QRScanMessage qrScanMessage) {
                        try {
                            switch (qrScanMessage.getResult()) {
                                case Constant.MUSIC_FACE_SUCCESS:
                                case Constant.MUSIC_FACE_FAIL:
                                    resumeFlag.set(0);
                                    scan_status.setBackgroundResource(qrScanMessage.isOk() ? R.mipmap.img_scan_success : R.mipmap.img_scan_error);
                                    scan_res.setText(qrScanMessage.getMessage());
                                    BusToast.showToast2(BaseActivity.this, qrScanMessage.getMessage(), qrScanMessage.isOk());
//                                    resumeUI();
                                    CountTime.getInstance().startCnt(qrScanMessage.isOk() ? 3000 : 1500);
                                    break;
                                case Constant.RECOVERY_VIEW:
                                    scan_res.setText("欢迎人脸乘车");
                                    scan_status.setBackgroundResource(R.mipmap.img_scan_wait);
                                    break;
                                default:
                                    break;
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            SLog.d("BaseActivity(accept.java:271)Rx异常>" + e.toString());
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(@NonNull Throwable throwable) throws Exception {
                        SLog.d("BaseActivity(call.java:115)Rx异常>>" + throwable.toString());
                    }
                });
    }


    @SuppressLint("SetTextI18n")
    @Override
    public void onProgress(int what, final int progress, long fileCount, long speed) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                progress_text.setText(progress + "%");
            }
        });

    }

    @Override
    public void onFinish(int what, String filePath, String apkVersion, String effWay) {
        version.setTextColor(getResources().getColor(R.color.colorAccent));
        progress_text.setVisibility(View.GONE);
        ThreadFactory.getScheduledPool().stopTask("loop_check");
        if (TextUtils.equals(effWay, "1")) {
            AppUtils.updateApk(filePath);
            BusApp.getPosManager().setDownFinish(-1);
        } else {
            JSONObject json = new JSONObject();
            json.put("version", apkVersion);
            json.put("apkPath", filePath);
            BusApp.getPosManager().setDownFinish(100);
            BusApp.getPosManager().setAPKInfo(json.toJSONString());
        }
    }

    @Override
    public void onDownloadError(int what, final String exception) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                progress_text.setText(exception);
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (checkApkThread != null) {
            checkApkThread.setOnDownProgress(null);
        }
    }

    @Override
    public void onCallBack(FaceResult result) {
        // TODO Result 里面返回用户名称和uid(card_id )
//        NO_FACE,        // 图像中没有人脸信息
//                NO_FRONTFACE,    // 人脸角度不足
//                NO_MATCH_USER,  // 底库中没有搜索的指定阈值之上的特征信息
//                UIDS_TOO_MUCH,  // 更新特征uid过多
//                INTERNAL_ERROR, // 内部错误 待细化
        LogUtil.d("", "onCallBack() called with: result = [" + result + "]");
        SLog.e("BaseActivity(onCallBack.java:169)" + "onCallBack() called with: result = [" + result + "]");
        // TODO 验证通过后黑名单处理逻辑
        switch (result.getCode()) {
            case SUCCESS:
                // 成功 处理
                if (isBlackUser(result.getUid())) {
                    // 黑名单用户处理逻辑
                    SoundPoolUtil.play(Constant.MUSIC_FACE_FAIL);
                    QRScanMessage message = new QRScanMessage();
                    message.setResult(Constant.MUSIC_FACE_FAIL);
                    message.setOk(true);
                    message.setMessage("黑名单");
                    RxBus.getInstance().send(message);
                } else {
                    // 正常用户 提示用户乘车
                    SoundPoolUtil.play(Constant.MUSIC_FACE_SUCCESS);
                    QRScanMessage message = new QRScanMessage();
                    message.setResult(Constant.MUSIC_FACE_SUCCESS);
                    message.setOk(true);
                    message.setMessage("刷脸成功");
                    RxBus.getInstance().send(message);
                    ThreadFactory.getScheduledPool().execute(new WorkThread("real_time_push", result));
                }
                break;
            case NO_FACE:
                SLog.e("BaseActivity(onCallBack2.java:253)无人脸信息");
                break;
            default:
                // 其他情况处理  待定
                if (result.getCode() != FaceResult.Code.NO_FRONTFACE) {
                    SoundPoolUtil.play(Constant.MUSIC_FACE_FAIL);
                }
                QRScanMessage message = new QRScanMessage();
                message.setResult(Constant.MUSIC_FACE_FAIL);
                String res = result.getCode() == FaceResult.Code.NO_FRONTFACE ? "请对准摄像头" : "识别不通过";
                message.setMessage(res);
                message.setOk(false);
                RxBus.getInstance().send(message);
                break;
        }

    }

    private boolean isBlackUser(String uid) {
        return DBManager.checkFaceBlack(uid);
    }


    private void resumeUI() {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                scan_res.setText("欢迎人脸乘车");
                scan_status.setBackgroundResource(R.mipmap.img_scan_wait);
            }
        }, 3000);
    }


}
